<template>
  <van-datetime-picker
      v-model="currentDate"
      type="date"
      title="选择年月日"
      :min-date="minDate"
      :max-date="maxDate"
      @cancel="$emit('cancel')"
      @confirm="onConfirm"
  />
</template>

<script>
import { editUserProfile } from '@/api/user'
import { Toast } from 'vant'

export default {
  name: 'EditBirthday',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(Date.now()),
      currentDate: new Date(this.value === '' ? Date.now() : this.value)
    }
  },
  created () {

  },
  methods: {
    // 格式化时间
    formatDateTime (val) {
      const date = new Date(val)
      const y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? ('0' + m) : m
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      return `${y}-${m}-${d}`
    },
    async onConfirm (val) {
      const data = this.formatDateTime(val)
      try {
        await editUserProfile({
          birthday: data
        })
        Toast('更新成功')
        this.$emit('input', data)
        this.$emit('cancel')
      } catch (e) {
        Toast('网络错误')
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
